package inet.app.view.activity;

import inet.app.R;
import inet.app.common.XoSoConstants;
import inet.app.controller.database.DataBaseHandler;
import inet.app.controller.parser.Parser;
import inet.app.controller.parser.Parser_Live_MN;
import inet.app.controller.parser.Parser_Live_MT;
import inet.app.controller.parser.Parser_Push_MB;
import inet.app.controller.parser.Parser_Push_NT;
import inet.app.controller.parser.Parser_XsSync_Live;
import inet.app.model.lottery.GetLoto;
import inet.app.model.lottery.LotteryResult;
import inet.app.model.object.KqGiai_Item;
import inet.app.model.object.Veso_Item;
import inet.app.model.util.ProgressDialog;
import inet.app.model.util.Util;
import inet.app.view.activity.KetQuaFragment.KQTTThread;
import inet.app.view.adapter.ListVesoAdapter;
import inet.app.view.fragment.FragmentMB;
import inet.app.view.fragment.FragmentMN;
import inet.app.view.fragment.FragmentMT;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

/*public class VesoList extends BaseActivity implements OnClickListener*/
public class VesoList extends BaseFragmentActivity implements OnClickListener {
	boolean isTrungTT = false;
	Button btAddNew;
	TextView tvComment, tvfotter, tvTitle;
	ArrayList<KqGiai_Item> push;
	private String data_result;
	Veso_Item veso_item_push;
	LotteryResult lotteryresult;
	KqGiai_Item items, items_last;
	Dialog dialog, dlKetqua;
	int Red1 = Color.rgb(255, 0, 0);
	ListView lv_veso;
	boolean isRegister = false;
	private ArrayAdapter<Veso_Item> adapter;
	private DataBaseHandler db;
	String trunggiai = "", trunglan1 = "";
	private String vesoOndialog = "";
	private ArrayList<Veso_Item> list_veso;
	Intent intent_service;
	private String veso, code, date, ketqua, name;
	private ProgressDialog pdia;
	private boolean isRunning = true;
	protected Thread pushThread = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_veso);
		db = new DataBaseHandler(VesoList.this);
		pdia = new ProgressDialog(VesoList.this);
		initBase();
		initScreen();
		implement();
		getData();
		LoadListData();
		// Push notify
		this.pushThread = new Thread(new VeSoTTThread());
		this.pushThread.start();
	}

	public void getData() {
		Bundle rb = this.getIntent().getExtras();
		data_result = rb.getString("datasend");

		System.out.println("DATA RESULT ==============>>" + data_result);
		if (!data_result.equals("")
				&& !data_result.split("-")[3].contains("Chưa có kết quả")) {
			veso = data_result.split("-")[0];
			code = data_result.split("-")[1];
			date = data_result.split("-")[2];
			ketqua = data_result.split("-")[3];
			name = data_result.split("-")[4];

			DialogKetqua(VesoList.this, code, date, ketqua, name);
			dlKetqua.show();
		}
	}

	public void onResume() {
		// TODO Auto-generated method stub
		((MyApp) getApplication()).setRunning(true);
		if (((MyApp) getApplication()).isKill()) {
			stopThread();
			finish();
		}
		super.onResume();
	}

	public void stopThread() {
		isRunning = false;
		((MyApp) getApplication()).setRunning(false);
		if (pushThread != null) {
			pushThread.interrupt();
			pushThread = null;
		}
	}

	private void UpdateData(Intent intent) {
		list_veso = db.getVeSo();

		String json = intent.getStringExtra("broad");
		System.out.println("Push:" + json);

		Parser pp = new Parser();
		if (pp.getName(json).equals("XSSYNC_RESP")) {
			if (Util.onLiveTimeMN()) {
				Parser_Live_MN parserMN = new Parser_Live_MN();
				push = parserMN.getList(json);
			} else if (Util.onLiveTimeMT()) {
				Parser_Live_MT parserMT = new Parser_Live_MT();
				push = parserMT.getList(json);
			} else {
				Parser_XsSync_Live parser = new Parser_XsSync_Live();
				push = parser.getList(json);
			}
		}
		System.out.println("MA CODE PUSH " + push.get(0).getCode()
				+ push.get(0).getDate() + push.get(0).getName());
		for (int i = 0; i < list_veso.size(); i++) {
			for (int j = 0; j < push.size(); j++) {
				if (list_veso.get(i).getCode().equals(push.get(j).getCode())
						&& list_veso.get(i).getDate()
								.equals(push.get(j).getDate())) {
					items = push.get(j);
					lotteryresult = new LotteryResult(items.getGiaidb(),
							items.getGiai1(), items.getGiai2(),
							items.getGiai3(), items.getGiai4(),
							items.getGiai5(), items.getGiai6(),
							items.getGiai7(), items.getGiai8());
					Result_Veso(lotteryresult, list_veso.get(i));
				}

			}

		}

	}

	private void UpdateListVeso(String json) {
		list_veso = db.getVeSo();
		System.out.println("Push:" + json);

		Parser pp = new Parser();
		if (pp.getName(json).equals("XSSYNC_RESP")) {
			if (Util.onLiveTimeMN()) {
				Parser_Push_NT parserMN = new Parser_Push_NT();
				push = parserMN.getList(json);
			} else if (Util.onLiveTimeMT()) {
				Parser_Push_NT parserMT = new Parser_Push_NT();
				push = parserMT.getList(json);
			} else {
				Parser_Push_MB parser = new Parser_Push_MB();
				push = parser.getList(json);
			}
		}
		if (push != null) {
			System.out.println("MA CODE PUSH " + push.get(0).getCode()
					+ push.get(0).getDate() + push.get(0).getName());
			for (int i = 0; i < list_veso.size(); i++) {
				for (int j = 0; j < push.size(); j++) {
					if (list_veso.get(i).getCode()
							.equals(push.get(j).getCode())
							&& list_veso.get(i).getDate()
									.equals(push.get(j).getDate())) {
						System.out.println("DUNG RÔI====================TRUE");
						items = push.get(j);
						lotteryresult = new LotteryResult(items.getGiaidb(),
								items.getGiai1(), items.getGiai2(),
								items.getGiai3(), items.getGiai4(),
								items.getGiai5(), items.getGiai6(),
								items.getGiai7(), items.getGiai8());
						Result_Veso(lotteryresult, list_veso.get(i));
					} else {
						System.out.println("DANG SAI ================== SAI");
					}

				}

			}

		} else {
			System.out.println("PUSH NULL RỒI ===================))");
		}
	}

	private void Result_Veso(LotteryResult result, Veso_Item veso_Item) {
		// TODO Auto-generated method stub
		System.out.println("CHAY VAO 1");
		GetLoto getloto = new GetLoto();
		String numberfirts, numberend;
		Collection<String> cEndNumbers = getloto
				.getEndNumberOfLotteryResult(result);
		String endNumber = "";
		System.out.println("LIST NUMBER IN VE SO === >> "
				+ veso_Item.getListNumber());
		for (Iterator<String> it = cEndNumbers.iterator(); it.hasNext();) {
			endNumber = it.next();
			System.out.println("END NUMBER lÀ" + endNumber);
			String sosanh = endNumber.split(": ")[1].toString();
			if (veso_Item.getListNumber().contains(sosanh)) {
				System.out.println("CHAY VAO THAY ĐỔI ĐI==============>> ");
				isTrungTT = true;
				trunggiai += " " + endNumber;
				if (!trunglan1.equals(trunggiai)) {
					trunglan1 = trunggiai;
					veso_item_push = new Veso_Item(veso_Item.getListNumber(),
							veso_Item.getCode(), veso_Item.getDate(),
							trunggiai, veso_Item.getName());
					db.updateVeSo(veso_item_push);
					callNotify("Bạn đã trúng " + trunglan1);
					LoadListData();
				}
				trunggiai = "";
			}
		}
		if (!isTrungTT) {
			veso_item_push = new Veso_Item(veso_Item.getListNumber(),
					veso_Item.getCode(), veso_Item.getDate(),
					"Bạn không trúng", veso_Item.getName());
			db.updateVeSo(veso_item_push);
			callNotify("Bạn không trúng");
			LoadListData();
		}
	}

	private void callNotify(String ketqua) {
		CharSequence contentTitle = ketqua;
		Notification notifyDetails = new Notification(
				R.drawable.icon_kqxs, contentTitle,
				System.currentTimeMillis());
		CharSequence contentText = "Vào vé số để biết thêm chi tiết!";
		// CharSequence contentText = json;
		Intent notifyIntent = new Intent();
		PendingIntent intent = PendingIntent.getActivity(VesoList.this, 0,
				notifyIntent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK);

		notifyDetails.setLatestEventInfo(VesoList.this, contentTitle,
				contentText, intent);
		notifyDetails.flags |= Notification.FLAG_AUTO_CANCEL;
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		mNotificationManager.notify(0, notifyDetails);
	}

	private void initScreen() {
		// TODO Auto-generated method stub
		btAddNew = (Button) findViewById(R.id.btAddNew);
		lv_veso = (ListView) findViewById(R.id.lv_veso);
		tvComment = (TextView) findViewById(R.id.tvComment);
		tvComment.setVisibility(View.GONE);
		tvTitle = (TextView) findViewById(R.id.tvTitle);
		tvTitle.setText("Danh Sách Vé Số");
		// Load animation
		tvfotter = (TextView) findViewById(R.id.tvfotter);
		final Animation text_animation = AnimationUtils.loadAnimation(this,
				R.anim.custom_text_animation);
		tvfotter.startAnimation(text_animation);
		tvfotter.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				pdia.show();
				Intent myWebLink = new Intent(
						android.content.Intent.ACTION_VIEW);
				myWebLink.setData(Uri.parse("http://m.ole.vn/"));
				startActivity(myWebLink);
				pdia.dismiss();
			}
		});
	}

	private void implement() {
		// TODO Auto-generated method stub
		btAddNew.setOnClickListener(this);
	}

	private void LoadListData() {
		pdia.show();
		if (db.getCountVs() != 0) {
			list_veso = db.getVeSo();
			if (list_veso.size() != 0) {
				System.out.println("MAX LENGHT " + list_veso.size());
				tvComment.setVisibility(View.GONE);
				adapter = new ListVesoAdapter(VesoList.this, list_veso);
				lv_veso.setAdapter(adapter);
				pdia.dismiss();

			} else {
				tvComment.setVisibility(View.VISIBLE);
				pdia.dismiss();
			}
		} else {
			tvComment.setVisibility(View.VISIBLE);
			pdia.dismiss();
		}

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btAddNew:
			pdia.show();
			stopThread();
			Intent intentAddnew = new Intent(VesoList.this, VesoAddNew.class);
			startActivity(intentAddnew);
			pdia.dismiss();
			break;
		default:
			break;
		}
	}

	// Dialog Kết quả
	public void DialogKetqua(Context c, final String code, final String date,
			final String ketquasend, final String name) {
		String ContentKq = "";
		if (ketqua.contains("Không trúng giải")) {
			ContentKq = "Rất tiếc, bạn không trúng giải nào của đài " + name
					+ ", mở thưởng ngày " + date + "!";
		} else {
			ContentKq = "Xin chúc mừng, bạn đã trúng " + ketqua + " của đài "
					+ name + ", mở thưởng ngày " + date + "!";
		}
		dlKetqua = new Dialog(c);
		dlKetqua.requestWindowFeature(Window.FEATURE_LEFT_ICON);
		dlKetqua.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
		dlKetqua.setTitle("Kết quả vé số");
		dlKetqua.setContentView(R.layout.dialog_ketqua_ve);
		//
		dlKetqua.getWindow().setBackgroundDrawableResource(
				R.color.orange);
		dlKetqua.getWindow().setTitleColor(Red1);
		dlKetqua.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
				R.drawable.icon_title_warning);
		//
		TextView tvContent = (TextView) dlKetqua.findViewById(R.id.tvContent);
		tvContent.setText(ContentKq);

		Button btDong = (Button) dlKetqua.findViewById(R.id.btDong);
		btDong.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				dlKetqua.dismiss();
			}
		});

		Button btChitiet = (Button) dlKetqua.findViewById(R.id.btChitiet);
		btChitiet.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				System.out.println("Dữ liệu gửi đi ======= " + code + date
						+ "SỐ " + veso);
				pdia.show();
				Bundle rb = new Bundle();
				Intent intent = new Intent(VesoList.this, VesoDetail.class);
				rb.putString("code", code);
				rb.putString("date", date);
				rb.putString("listnumber", veso);
				intent.putExtras(rb);
				startActivity(intent);
				pdia.dismiss();
				dlKetqua.dismiss();
			}
		});
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			System.out.println("THOAT NHE");
			quitDialog(VesoList.this);
			dlquit.show();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	public void quitDialog(Context c) {
		dlquit = new Dialog(c);
		dlquit.requestWindowFeature(Window.FEATURE_LEFT_ICON);
		dlquit.setTitle("Thoát ứng dụng ?");
		dlquit.setContentView(R.layout.dialog_quit);
		dlquit.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
		dlquit.getWindow().setBackgroundDrawable(
				new ColorDrawable(Color.rgb(50, 50, 50)));
		dlquit.getWindow().setTitleColor(XoSoConstants.White);
		dlquit.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
				R.drawable.icon_registersc);

		Button huy = (Button) dlquit.findViewById(R.id.bthuy);
		huy.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				dlquit.dismiss();
			}
		});

		Button quit = (Button) dlquit.findViewById(R.id.btquit);
		quit.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				stopThread();
				((MyApp) getApplication()).setKill(true);
				finish();
				dlquit.dismiss();
			}
		});
	}

	Handler myUpdateHandler = new Handler() {
		@SuppressWarnings("deprecation")
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == 0) {
				String json = (String) msg.obj;
				System.out.println("===>PUSH VE SO :" + json);
				UpdateListVeso(json);
			}
		}
	};

	class VeSoTTThread implements Runnable {
		public void run() {
			Socket s = null;
			DataInputStream _inFromMaster = null;
			byte[] buff = null;
			int buffLength;
			int bs;
			String strResult = "";
			// endcode
			try {
				s = ((MyApp) getApplication()).get_socket();
				System.out.println("Giá trị của socket là  " + s);
				_inFromMaster = new DataInputStream(s.getInputStream());
				System.out.println("Giá trị IN FORM MASTER "
						+ _inFromMaster.available());
			} catch (Exception e) {
				// System.out.println(e.getMessage());
				// LogFile
				// e.fillInStackTrace();
				// e.printStackTrace();
			}
			while (isRunning && s != null) {
				try {
					while (_inFromMaster.available() > 0) {
						bs = _inFromMaster.available(); // get the amount of
						buff = new byte[bs];
						buffLength = buff.length;
						_inFromMaster.read(buff, 0, buffLength);
						strResult = strResult + new String(buff);
						// strResult
						// ="XSSYNC_RESP|0|09/12/2013 10:10:17|XSTD|09/12/2013 18:24:09|1:71563|2:38328-30031|3:30167-15518-64844-44379-96172-30523|4:2638-6471-9699-3504|5:8844-6020-9822-9467-6544-6270|6:706-722-959|7:02-75-88-92|8:|0:66666||\r\n";
						// strResult
						// ="XSSYNC_RESP|0|07/12/2013 10:10:17|XSVL|06/12/2013 18:24:09|1:71563|2:38328|3:30167-15518|4:2638-6471-9699-3504-64844-44379-96172|5:8844|6:7036-7223-9594|7:022|8:85|0:666666||\r\n";
						// try {
						// Thread.sleep(10000);
						// } catch (InterruptedException e) {
						// // TODO Auto-generated catch block
						// e.printStackTrace();
						// }
						System.out.println("LIVE ==>> : " + strResult);
						// LogFile
						Util.Log2File(strResult);
						if (strResult.endsWith("\r\n"))
							break;

					}
					if (strResult != null
							&& !"".equalsIgnoreCase(strResult.trim())) {
						Message msg = myUpdateHandler.obtainMessage(0,
								strResult);
						myUpdateHandler.sendMessage(msg);
						strResult = "";
					}
				} catch (IOException ex) {
					System.out.println(ex.getMessage());
					ex.fillInStackTrace();
					Message msg = myUpdateHandler.obtainMessage(1);
					myUpdateHandler.sendMessage(msg);
				}

			}
		}
	}
}
